import { createRouter, createWebHistory } from 'vue-router';
import UserLayout from '@/layout/UserLayout.vue';
import PageLayout from '@/layout/UserLayout.vue';
import TableLayout from '@/layout/TableLayout.vue';
import { LOGIN_PAGE_PATH, HOME_PAGE_PATH } from '@/mutation-type';

const modules = import.meta.globEager('./modules/*.js');
const menu = [];
Object.keys(modules).forEach(key => {
	if (key.includes('/_')) {
		return;
	}
	const mod = modules[key].default || {};
	const modList = Array.isArray(mod) ? [...mod] : [mod];
	menu.push(...modList);
});

const routes = [
	{
		path: '/',
		component: TableLayout,
		redirect: HOME_PAGE_PATH
	},
	...menu,
	{
		path: '/user',
		component: UserLayout,
		redirect: LOGIN_PAGE_PATH,
		hidden: true,
		children: [
			{
				path: 'login',
				name: 'login',
				component: () => import('@/views/Login/index.vue')
			}
		]
	},
	{
		path: '/404',
		component: () => import('@/views/404/index.vue')
	},
	{
		path: '/:catchAll(.*)',
		redirect: '/404'
	}
];

const router = createRouter({
	history: createWebHistory(import.meta.env.VITE_PUBLIC_PATH),
	routes,
	strict: true,
	scrollBehavior(to, from, savedPosition) {
		return new Promise(resolve => {
			if (savedPosition) {
				return savedPosition;
			} else {
				if (from.meta.saveSrollTop) {
					const top = document.documentElement.scrollTop || document.body.scrollTop;
					resolve({ left: 0, top });
				}
			}
		});
	}
});
export { menu };
export default router;
